extends Control

# 游戏系统引用
var save_system: SaveSystem
var time_system: TimeSystem
var crop_system: CropSystem
var input_adapter: InputAdapter
var inventory: Inventory
var economy: Economy
var field_system: FieldSystem
var log_system: LogSystem

# UI引用
var tile_map: TileMap
var inventory_panel: Control
var shop_panel: Control
var message_toast: Control
var log_viewer: Control

# 游戏状态
var current_tool := "hoe"
var player_money := 100
var player_stamina := 100
var max_stamina := 100

func _ready():
	print("Farm场景初始化开始")
	
	# 初始化系统
	setup_systems()
	setup_ui()
	
	# 加载游戏数据
	load_game()
	
	# 初始化农田显示
	setup_tilemap()
	update_field_display()
	update_hud()
	
	log_system.info("Farm场景初始化完成", "Farm")

func setup_systems():
	# 创建系统实例
	save_system = SaveSystem.new()
	time_system = TimeSystem.new()
	crop_system = CropSystem.new()
	input_adapter = InputAdapter.new()
	inventory = Inventory.new()
	economy = Economy.new()
	field_system = FieldSystem.new()
	log_system = LogSystem.new()
	
	# 添加到场景树
	add_child(save_system)
	add_child(time_system)
	add_child(crop_system)
	add_child(input_adapter)
	add_child(inventory)
	add_child(economy)
	add_child(field_system)
	add_child(log_system)
	
	# 记录系统初始化
	log_system.info("所有游戏系统已初始化", "Farm")
	
	# 连接系统
	time_system.time_changed.connect(_on_time_changed)
	input_adapter.action_requested.connect(_on_action_requested)
	
	# 设置系统关联
	economy.set_inventory(inventory)
	economy.set_crop_system(crop_system)
	field_system.set_time_system(time_system)
	field_system.set_crop_system(crop_system)
	field_system.set_inventory(inventory)
	
	log_system.info("系统关联设置完成", "Farm")

func setup_ui():
	print("开始设置UI")
	
	# 安全获取TileMap引用
	tile_map = get_node_or_null("GameRoot/FieldTileMap")
	if tile_map:
		print("找到TileMap")
	else:
		print("未找到TileMap")
	
	# 创建UI面板
	create_inventory_panel()
	create_shop_panel()
	create_message_toast()
	create_log_viewer()
	
	# 连接按钮信号
	connect_ui_buttons()
	
	log_system.info("UI设置完成", "Farm")

func connect_ui_buttons():
	print("连接UI按钮信号")
	
	# 连接右侧按钮
	var inventory_btn = get_node_or_null("UIRoot/HUD/RightPanel/InventoryButton")
	if inventory_btn:
		inventory_btn.pressed.connect(_on_inventory_button_pressed)
		print("背包按钮已连接")
	
	var shop_btn = get_node_or_null("UIRoot/HUD/RightPanel/ShopButton")
	if shop_btn:
		shop_btn.pressed.connect(_on_shop_button_pressed)
		print("商店按钮已连接")
	
	var save_btn = get_node_or_null("UIRoot/HUD/RightPanel/SaveButton")
	if save_btn:
		save_btn.pressed.connect(_on_save_button_pressed)
		print("保存按钮已连接")
	
	var menu_btn = get_node_or_null("UIRoot/HUD/RightPanel/MenuButton")
	if menu_btn:
		menu_btn.pressed.connect(_on_menu_button_pressed)
		print("菜单按钮已连接")
	
	# 连接底部工具栏按钮
	var toolbar = get_node_or_null("UIRoot/HUD/ToolBar")
	if toolbar:
		var hoe_btn = toolbar.get_node_or_null("HoeButton")
		if hoe_btn:
			hoe_btn.pressed.connect(func(): _on_tool_selected("hoe"))
			print("锄头按钮已连接")
		
		var water_btn = toolbar.get_node_or_null("WaterButton")
		if water_btn:
			water_btn.pressed.connect(func(): _on_tool_selected("water"))
			print("水壶按钮已连接")
		
		var seed1_btn = toolbar.get_node_or_null("Seed1Button")
		if seed1_btn:
			seed1_btn.pressed.connect(func(): _on_tool_selected("seed_turnip"))
			print("萝卜种子按钮已连接")
		
		var seed2_btn = toolbar.get_node_or_null("Seed2Button")
		if seed2_btn:
			seed2_btn.pressed.connect(func(): _on_tool_selected("seed_potato"))
			print("土豆种子按钮已连接")
		
		var seed3_btn = toolbar.get_node_or_null("Seed3Button")
		if seed3_btn:
			seed3_btn.pressed.connect(func(): _on_tool_selected("seed_corn"))
			print("玉米种子按钮已连接")
		
		var harvest_btn = toolbar.get_node_or_null("HarvestButton")
		if harvest_btn:
			harvest_btn.pressed.connect(func(): _on_tool_selected("harvest"))
			print("收割按钮已连接")
	
	print("所有按钮信号连接完成")

func setup_tilemap():
	if not tile_map:
		print("TileMap不存在，无法设置")
		return
	
	print("设置TileMap")
	
	# 设置TileMap缩放，让农田显示更大
	tile_map.scale = Vector2(3.0, 3.0)  # 放大3倍
	tile_map.position = Vector2(20, 20)  # 调整位置
	
	# 创建TileSet
	var tileset = TileSet.new()
	var source = TileSetAtlasSource.new()
	
	# 创建简单的纹理图集，增加分割线
	var image = Image.create(128, 32, false, Image.FORMAT_RGBA8)
	
	# 绿色瓦片 (草地，带黑色边框)
	for x in range(32):
		for y in range(32):
			var color = Color.GREEN
			# 添加黑色边框 (边缘2像素宽)
			if x < 2 or x > 29 or y < 2 or y > 29:
				color = Color(0, 0, 0, 1)  # 黑色边框
			image.set_pixel(x, y, color)
	
	# 棕色瓦片 (耕地，带黑色边框)
	for x in range(32, 64):
		for y in range(32):
			var color = Color(0.6, 0.3, 0.1)  # 棕色
			# 添加黑色边框 (边缘2像素宽)
			if x < 34 or x > 61 or y < 2 or y > 29:
				color = Color(0, 0, 0, 1)  # 黑色边框
			image.set_pixel(x, y, color)
	
	# 黄色瓦片 (作物，带黑色边框)
	for x in range(64, 96):
		for y in range(32):
			var color = Color.YELLOW
			# 添加黑色边框 (边缘2像素宽)
			if x < 66 or x > 93 or y < 2 or y > 29:
				color = Color(0, 0, 0, 1)  # 黑色边框
			image.set_pixel(x, y, color)
	
	# 湿润的耕地 (深棕色，带黑色边框)
	for x in range(96, 128):
		for y in range(32):
			var color = Color(0.4, 0.2, 0.05)  # 深棕色表示湿润
			# 添加黑色边框 (边缘2像素宽)
			if x < 98 or x > 125 or y < 2 or y > 29:
				color = Color(0, 0, 0, 1)  # 黑色边框
			image.set_pixel(x, y, color)
	
	# 创建ImageTexture
	var texture = ImageTexture.create_from_image(image)
	
	# 设置纹理和区域大小
	source.texture = texture
	source.texture_region_size = Vector2i(32, 32)
	
	# 创建瓦片
	source.create_tile(Vector2i(0, 0))  # 草地
	source.create_tile(Vector2i(1, 0))  # 耕地
	source.create_tile(Vector2i(2, 0))  # 作物
	source.create_tile(Vector2i(3, 0))  # 湿润的耕地
	
	# 添加源并设置TileMap
	tileset.add_source(source, 0)
	tile_map.tile_set = tileset
	
	log_system.info("TileMap设置完成，添加了分割线", "Farm")
	print("TileMap设置完成，缩放:", tile_map.scale)

func create_inventory_panel():
	inventory_panel = preload("res://ui/InventoryPanel.tscn").instantiate()
	$UIRoot.add_child(inventory_panel)
	inventory_panel.visible = false
	inventory_panel.position = Vector2(400, 200)

func create_shop_panel():
	shop_panel = preload("res://ui/ShopPanel.tscn").instantiate()
	$UIRoot.add_child(shop_panel)
	shop_panel.visible = false
	shop_panel.position = Vector2(300, 150)

func create_message_toast():
	message_toast = preload("res://ui/MessageToast.tscn").instantiate()
	$UIRoot.add_child(message_toast)

func create_log_viewer():
	log_viewer = preload("res://ui/LogViewer.tscn").instantiate()
	$UIRoot.add_child(log_viewer)
	log_viewer.visible = false

# 简化的输入处理
func _input(event):
	# 处理鼠标点击
	if event is InputEventMouseButton and event.pressed and event.button_index == MOUSE_BUTTON_LEFT:
		log_system.debug("检测到鼠标左键点击: " + str(event.position), "Input")
		
		# 检查面板状态
		if inventory_panel and inventory_panel.visible:
			log_system.debug("背包面板打开，忽略地块交互", "Input")
			return
		if shop_panel and shop_panel.visible:
			log_system.debug("商店面板打开，忽略地块交互", "Input")
			return
		
		# 更精确的UI区域检查
		var screen_size = get_viewport().size
		
		# 检查是否点击在右侧按钮区域 (更精确的范围)
		if event.position.x > screen_size.x - 150 and event.position.y < 200:
			log_system.debug("点击在右侧按钮区域，忽略地块交互", "Input")
			# 尝试处理右侧按钮点击
			handle_right_panel_click(event.position)
			return
		
		# 检查是否点击在底部工具栏区域
		if event.position.y > screen_size.y - 60:
			log_system.debug("点击在工具栏区域，忽略地块交互", "Input")
			return
		
		# 处理地块交互
		log_system.debug("处理地块交互", "Input")
		handle_field_interaction(event.position)
	
	# 处理键盘快捷键
	elif event is InputEventKey and event.pressed:
		var key_name = OS.get_keycode_string(event.keycode)
		log_system.debug("检测到键盘按键: " + key_name, "Input")
		
		match event.keycode:
			KEY_1:
				log_system.debug("选择工具: 锄头", "Input")
				_on_tool_selected("hoe")
			KEY_2:
				log_system.debug("选择工具: 水壶", "Input")
				_on_tool_selected("water")
			KEY_3:
				log_system.debug("选择工具: 萝卜种子", "Input")
				_on_tool_selected("seed_turnip")
			KEY_4:
				log_system.debug("选择工具: 土豆种子", "Input")
				_on_tool_selected("seed_potato")
			KEY_5:
				log_system.debug("选择工具: 玉米种子", "Input")
				_on_tool_selected("seed_corn")
			KEY_6:
				log_system.debug("选择工具: 收割工具", "Input")
				_on_tool_selected("harvest")
			KEY_I:
				log_system.debug("切换背包面板", "Input")
				toggle_inventory_panel()
			KEY_O:
				log_system.debug("切换商店面板", "Input")
				toggle_shop_panel()
			KEY_L:
				log_system.debug("切换日志查看器", "Input")
				toggle_log_viewer()

func handle_field_interaction(screen_pos: Vector2):
	log_system.debug("处理地块交互，屏幕坐标: " + str(screen_pos), "Farm")
	
	if not tile_map:
		log_system.error("TileMap 不存在", "Farm")
		return
	
	# 添加更多调试信息，帮助诊断坐标转换问题
	log_system.debug("TileMap位置: " + str(tile_map.position) + " 缩放: " + str(tile_map.scale), "Farm")
	
	# 改进坐标转换逻辑，使用全局变换矩阵进行更精确的坐标转换
	var global_transform = tile_map.get_global_transform()
	var local_pos = global_transform.affine_inverse() * screen_pos
	var tile_pos = tile_map.local_to_map(local_pos)
	
	# 记录详细的坐标转换过程
	log_system.debug("全局变换: " + str(global_transform), "Farm")
	log_system.debug("局部坐标: " + str(local_pos) + " 瓦片坐标: " + str(tile_pos), "Farm")
	log_system.debug("农田大小: %dx%d, 点击位置: (%d,%d)" % [field_system.field_width, field_system.field_height, tile_pos.x, tile_pos.y], "Farm")
	
	# 添加边界容错，允许轻微的边界误差
	var tolerance = 1  # 允许1个单位的误差
	var in_bounds_with_tolerance = (
		tile_pos.x >= -tolerance and 
		tile_pos.x < field_system.field_width + tolerance and 
		tile_pos.y >= -tolerance and 
		tile_pos.y < field_system.field_height + tolerance
	)
	
	# 如果在容错范围内，调整到有效范围
	if in_bounds_with_tolerance:
		var adjusted_tile_pos = Vector2i(
			clamp(tile_pos.x, 0, field_system.field_width - 1),
			clamp(tile_pos.y, 0, field_system.field_height - 1)
		)
		
		if tile_pos != adjusted_tile_pos:
			log_system.info("坐标在容错范围内，已调整: (%d,%d) -> (%d,%d)" % 
				[tile_pos.x, tile_pos.y, adjusted_tile_pos.x, adjusted_tile_pos.y], "Farm")
			tile_pos = adjusted_tile_pos
		
		log_system.debug("坐标有效，使用工具: " + current_tool, "Farm")
		
		# 使用当前工具
		if field_system.use_tool(current_tool, tile_pos):
			log_system.info("工具使用成功: %s 在位置 (%d,%d)" % [get_tool_name(current_tool), tile_pos.x, tile_pos.y], "Farm")
			update_field_display()
			show_message("使用 %s 在位置 (%d,%d)" % [get_tool_name(current_tool), tile_pos.x, tile_pos.y])
			update_hud()
		else:
			log_system.warning("工具使用失败: %s 在位置 (%d,%d)" % [get_tool_name(current_tool), tile_pos.x, tile_pos.y], "Farm")
			show_message("无法在此位置使用 %s" % get_tool_name(current_tool))
	else:
		# 添加更详细的错误信息
		var reason = ""
		if tile_pos.x < 0 or tile_pos.x >= field_system.field_width:
			reason += "X坐标超出范围"
		if tile_pos.y < 0 or tile_pos.y >= field_system.field_height:
			if reason != "":
				reason += "，"
			reason += "Y坐标超出范围"
		
		log_system.warning("坐标超出范围: (%d,%d), 农田大小: %dx%d, 原因: %s" % [tile_pos.x, tile_pos.y, field_system.field_width, field_system.field_height, reason], "Farm")
		show_message("点击位置超出农田范围")

func get_tool_name(tool: String) -> String:
	match tool:
		"hoe": return "锄头"
		"water": return "水壶"
		"seed_turnip": return "萝卜种子"
		"seed_potato": return "土豆种子"
		"seed_corn": return "玉米种子"
		"harvest": return "收割工具"
		_: return tool

func _on_action_requested(action: String, pos: Vector2):
	match action:
		"interact":
			handle_field_interaction(pos)
		"tool_hoe":
			_on_tool_selected("hoe")
		"tool_water":
			_on_tool_selected("water")
		"tool_seed_1":
			_on_tool_selected("seed_turnip")
		"tool_seed_2":
			_on_tool_selected("seed_potato")
		"tool_seed_3":
			_on_tool_selected("seed_corn")
		"tool_harvest":
			_on_tool_selected("harvest")

func _on_tool_selected(tool: String):
	current_tool = tool
	show_message("选择工具: %s" % get_tool_name(tool))
	update_toolbar_display()

func update_toolbar_display():
	# 更新工具栏按钮状态
	var toolbar = get_node_or_null("UIRoot/HUD/ToolBar")
	if not toolbar:
		return
	
	var buttons = ["HoeButton", "WaterButton", "Seed1Button", "Seed2Button", "Seed3Button", "HarvestButton"]
	var tools = ["hoe", "water", "seed_turnip", "seed_potato", "seed_corn", "harvest"]
	
	for i in range(buttons.size()):
		var btn = toolbar.get_node_or_null(buttons[i])
		if btn:
			if tools[i] == current_tool:
				btn.modulate = Color.YELLOW
			else:
				btn.modulate = Color.WHITE

func toggle_inventory_panel():
	if inventory_panel:
		inventory_panel.visible = !inventory_panel.visible
		if inventory_panel.visible:
			# 使用正确的方法调用背包面板
			if inventory_panel.has_method("show_panel"):
				inventory_panel.show_panel(inventory)
			else:
				# 兼容旧版本
				inventory_panel.inventory = inventory
				inventory_panel.update_display()
			show_message("打开背包")
		else:
			show_message("关闭背包")

func toggle_shop_panel():
	if shop_panel:
		shop_panel.visible = !shop_panel.visible
		if shop_panel.visible:
			# 使用正确的方法调用商店面板
			if shop_panel.has_method("show_panel"):
				shop_panel.show_panel(economy)
				# 设置玩家金钱（如果需要）
				if economy.has_method("set_player_money"):
					economy.set_player_money(player_money)
			else:
				# 兼容旧版本
				shop_panel.economy = economy
				shop_panel.update_display()
			show_message("打开商店")
		else:
			show_message("关闭商店")

func toggle_log_viewer():
	if log_viewer:
		log_viewer.visible = !log_viewer.visible
		if log_viewer.visible:
			if log_viewer.has_method("show_panel"):
				log_viewer.show_panel(log_system)
			show_message("打开日志查看器")
			log_system.info("日志查看器已打开", "UI")
		else:
			show_message("关闭日志查看器")
			log_system.info("日志查看器已关闭", "UI")

func save_game():
	log_system.info("开始保存游戏数据", "Save")
	
	var save_data = {
		"money": player_money,
		"stamina": player_stamina,
		"time": {
			"day": time_system.current_day,
			"hour": time_system.current_hour
		},
		"field": field_system.get_save_data(),
		"inventory": inventory.get_save_data()
	}
	
	# save_game方法是void类型，不返回值
	save_system.save_game(save_data)
	
	# 我们可以通过连接save_system的信号来处理保存成功的情况
	log_system.info("游戏数据保存请求已发送", "Save")
	show_message("游戏已保存")

func load_game():
	log_system.info("开始加载游戏数据", "Load")
	
	var save_data = save_system.load_game()
	
	# GDScript没有try-except语法，使用条件检查代替
	if save_data != null:
		if save_data.has("money"):
			player_money = save_data.money
			log_system.debug("加载金钱数据: " + str(player_money), "Load")
		
		if save_data.has("stamina"):
			player_stamina = save_data.stamina
			log_system.debug("加载体力数据: " + str(player_stamina), "Load")
		
		if save_data.has("time"):
			time_system.current_day = save_data.time.get("day", 1)
			time_system.current_hour = save_data.time.get("hour", 8)
			log_system.debug("加载时间数据: 第%d天 %02d:00" % [time_system.current_day, time_system.current_hour], "Load")
		
		if save_data.has("field"):
			field_system.load_from_data(save_data.field)
			log_system.debug("加载农田数据成功", "Load")
		
		if save_data.has("inventory"):
			if inventory.has_method("load_from_data"):
				inventory.load_from_data(save_data.inventory)
				log_system.debug("加载背包数据成功", "Load")
			else:
				log_system.warning("Inventory没有load_from_data方法，跳过背包数据加载", "Load")
		
		log_system.info("游戏数据加载完成", "Load")
	else:
		log_system.error("加载游戏数据失败", "Load")

func return_to_menu():
	save_game()
	show_message("返回主菜单")
	await get_tree().create_timer(1.0).timeout
	get_tree().change_scene_to_file("res://scenes/Main.tscn")

func _on_time_changed(_day: int, hour: int):
	# FieldSystem会自己处理作物生长，不需要手动调用
	update_field_display()
	update_hud()
	
	# 体力恢复
	if hour == 8:  # 每天早上8点恢复体力
		player_stamina = max_stamina
		show_message("新的一天开始！体力已恢复")

func update_field_display():
	if not tile_map:
		print("TileMap 未找到")
		return
	
	log_system.debug("开始更新农田显示", "Farm")
	
	# 清除现有瓦片
	tile_map.clear()
	
	# 获取当前游戏时间
	var current_time = time_system.get_game_time_stamp() if time_system else 0
	
	# 绘制农田网格
	for y in range(field_system.field_height):
		for x in range(field_system.field_width):
			var tile_data = field_system.get_tile(Vector2i(x, y))
			var atlas_coords = Vector2i(0, 0)  # 默认绿色草地
			
			if tile_data.plowed:
				# 检查是否湿润 (wet_until > current_time)
				if tile_data.has("wet_until") and tile_data.wet_until > current_time:
					atlas_coords = Vector2i(3, 0)  # 湿润的耕地（深棕色）
				else:
					atlas_coords = Vector2i(1, 0)  # 普通耕地（棕色）
			
			if tile_data.crop_id != null and tile_data.crop_id != "":
				atlas_coords = Vector2i(2, 0)  # 黄色作物
			
			# 设置瓦片
			tile_map.set_cell(0, Vector2i(x, y), 0, atlas_coords)
	
	log_system.info("农田显示更新完成: %dx%d 瓦片，带分割线" % [field_system.field_width, field_system.field_height], "Farm")

func update_hud():
	var hud = get_node_or_null("UIRoot/HUD")
	if not hud:
		return
	
	var money_label = hud.get_node_or_null("TopBar/MoneyLabel")
	if money_label:
		money_label.text = "金币: %d" % player_money
	
	var stamina_label = hud.get_node_or_null("TopBar/StaminaLabel")
	if stamina_label:
		stamina_label.text = "体力: %d/%d" % [player_stamina, max_stamina]
	
	var time_label = hud.get_node_or_null("TopBar/TimeLabel")
	if time_label:
		time_label.text = "第%d天 %02d:00" % [time_system.current_day, time_system.current_hour]

func show_message(text: String):
	print(text)
	if log_system:
		log_system.info(text, "Message")
	if message_toast:
		message_toast.show_message(text)

# Farm.tscn中连接的信号处理方法
func _on_tool_button_pressed(tool: String):
	_on_tool_selected(tool)

func _on_inventory_button_pressed():
	toggle_inventory_panel()

func _on_shop_button_pressed():
	toggle_shop_panel()

func _on_save_button_pressed():
	save_game()

func _on_menu_button_pressed():
	return_to_menu()

func _notification(what):
	if what == NOTIFICATION_WM_CLOSE_REQUEST:
		save_game()
		get_tree().quit()

func handle_right_panel_click(position: Vector2):
	log_system.debug("处理右侧面板点击，位置: " + str(position), "UI")
	
	# 获取右侧面板 - 检查两种可能的节点路径
	var menu_buttons = get_node_or_null("UIRoot/HUD/MenuButtons")
	if not menu_buttons:
		menu_buttons = get_node_or_null("UIRoot/HUD/RightPanel")
		if not menu_buttons:
			log_system.error("找不到右侧菜单按钮", "UI")
			return false
	
	# 记录找到的节点路径
	log_system.debug("找到右侧面板: " + str(menu_buttons.get_path()), "UI")
	
	# 获取按钮引用
	var inventory_btn = menu_buttons.get_node_or_null("InventoryButton")
	var shop_btn = menu_buttons.get_node_or_null("ShopButton")
	var save_btn = menu_buttons.get_node_or_null("SaveButton")
	var menu_btn = menu_buttons.get_node_or_null("MenuButton")
	
	# 记录找到的按钮
	if inventory_btn:
		log_system.debug("找到背包按钮: " + str(inventory_btn.get_path()), "UI")
	if shop_btn:
		log_system.debug("找到商店按钮: " + str(shop_btn.get_path()), "UI")
	if save_btn:
		log_system.debug("找到保存按钮: " + str(save_btn.get_path()), "UI")
	if menu_btn:
		log_system.debug("找到菜单按钮: " + str(menu_btn.get_path()), "UI")
	
	# 转换为局部坐标
	var local_pos = menu_buttons.get_global_transform().affine_inverse() * position
	log_system.debug("菜单按钮局部坐标: " + str(local_pos), "UI")
	
	# 检查点击了哪个按钮 - 使用更精确的检测方法
	if inventory_btn:
		var rect = Rect2(inventory_btn.position, inventory_btn.size)
		if rect.has_point(local_pos):
			log_system.info("点击了背包按钮", "UI")
			_on_inventory_button_pressed()
			return true
	
	if shop_btn:
		var rect = Rect2(shop_btn.position, shop_btn.size)
		if rect.has_point(local_pos):
			log_system.info("点击了商店按钮", "UI")
			_on_shop_button_pressed()
			return true
	
	if save_btn:
		var rect = Rect2(save_btn.position, save_btn.size)
		if rect.has_point(local_pos):
			log_system.info("点击了保存按钮", "UI")
			_on_save_button_pressed()
			return true
	
	if menu_btn:
		var rect = Rect2(menu_btn.position, menu_btn.size)
		if rect.has_point(local_pos):
			log_system.info("点击了菜单按钮", "UI")
			_on_menu_button_pressed()
			return true
	
	log_system.debug("没有点击到任何右侧按钮", "UI")
	return false
